﻿using System;
using VegetableSale.NET.Dao;
using VegetableSale.NET.Entities;

namespace VegetableSale.NET.Services;

public class SaleService
{
    private SaleMapper saleMapper = new SaleMapper();

    private GoodService goodService = new GoodService();

    public Result getSaleList(QueryDTO queryDTO)
    {
        SalePage salePage = new SalePage();
        uint pageNo = queryDTO.PageNo;
        uint pageSize = queryDTO.PageSize;
        List<Sale> sales = saleMapper.getSaleList(queryDTO);
        List<Sale> returnSales = new List<Sale>();

        if (pageSize * pageNo - 1 >= sales.Count)
        {
            for (uint i = pageSize * (pageNo - 1); i <= sales.Count - 1; i++)
            {
                Sale sale = sales[(int)i];
                returnSales.Add(sale);
            }
        }
        else
        {
            for (uint i = pageSize * (pageNo - 1); i <= pageSize * pageNo - 1; i++)
            {
                Sale sale = sales[(int)i];
                returnSales.Add(sale);
            }
        }

        salePage.Records = returnSales;
        salePage.Pages = (int)pageNo;
        salePage.Size = pageSize;
        salePage.Total = (uint)sales.Count;

        return new Result(200, "搜索成功", salePage);
    }

    public Result deleteSale(int id)
    {
        List<Object> updateList = saleMapper.getSaleMountById(id);
        GoodService goodService = new GoodService();
        goodService.updateInventory((int)updateList[0],(int)updateList[1],"+");
        saleMapper.deleteSale(id);
        return new Result(200, "删除成功", "");
    }
    
    public Result saleAllGood()
    {
        return new Result(0,"操作成功",saleMapper.saleAllGood());
    }

    public Result addSale(SaleQuery saleQuery)
    {
        double inventory = saleMapper.getInventoryById(saleQuery.Commid);
        if (inventory<saleQuery.Salemount)
        {
            return new Result(201, "库存不足", "");
        }
        else
        {
            goodService.updateInventory(saleQuery.Commid, saleQuery.Salemount, "-");
            saleMapper.addSale(saleQuery);
            return new Result(200, "操作成功", "");
        }
    }

    public Result updateSale(SaleUpdateQuery saleUpdateQuery)
    {
        Sale sale = saleMapper.getSaleById(saleUpdateQuery.Id);

        if (saleUpdateQuery.Salemount>=sale.Salemount)
        {
            int change = saleUpdateQuery.Salemount - sale.Salemount;
            goodService.updateInventory(saleUpdateQuery.Commid,change,"-");
        }
        else
        {
            int change = sale.Salemount - saleUpdateQuery.Salemount;
            goodService.updateInventory(saleUpdateQuery.Commid,change,"+");
        }

        saleMapper.updateSale(saleUpdateQuery);

        return new Result(200, "操作成功", "");
    }


}

